package com.zlc.common.core.dept.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zlc.common.common.service.BaseServiceImpl;
import com.zlc.common.core.dept.mapper.MayanPlatDeptMapper;
import com.zlc.common.core.dept.model.entity.MayanPlatDept;
import com.zlc.common.core.dept.model.vo.MayanPlatDeptVo;
import com.zlc.common.core.dept.service.MayanPlatDeptService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author  zl
 * @date 2023-05-08 
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class MayanPlatDeptServiceImpl extends BaseServiceImpl<MayanPlatDeptMapper, MayanPlatDept, MayanPlatDeptVo> implements MayanPlatDeptService {

    @Override
    public MayanPlatDeptVo getByDeptCode(String deptCode) {
        LambdaQueryWrapper<MayanPlatDept> wrapper = wrapper().eq(MayanPlatDept::getDeptCode, deptCode);
        return queryOne(wrapper);
    }

    @Override
    public MayanPlatDeptVo getByDeptNo(String deptNo) {
        LambdaQueryWrapper<MayanPlatDept> wrapper = wrapper().eq(MayanPlatDept::getDeptNo, deptNo);
        return queryOne(wrapper);
    }

    @Override
    public MayanPlatDeptVo getByDeptId(String deptId) {
        LambdaQueryWrapper<MayanPlatDept> wrapper = wrapper().eq(MayanPlatDept::getDeptId, deptId);
        return queryOne(wrapper);
    }

    private List<MayanPlatDeptVo> getByParentId(String parentId){
        LambdaQueryWrapper<MayanPlatDept> wrapper = wrapper().eq(MayanPlatDept::getParentDeptId, parentId);
        return queryVoList(wrapper);
    }

    /**
     * 查询所有子部门信息
     */
    @Override
    public List<MayanPlatDeptVo> getChildDept(String deptCode){
        MayanPlatDeptVo deptVo = getByDeptCode(deptCode);
        if(ObjectUtils.isEmpty(deptVo)){
            return new ArrayList<>();
        }
        List<MayanPlatDeptVo> deptVos = new ArrayList<>(Collections.singletonList(deptVo));
        loadChildDept(deptVo,deptVos);
        return deptVos;
    }

    private void loadChildDept(MayanPlatDeptVo parentDept,List<MayanPlatDeptVo> allDept){
        List<MayanPlatDeptVo> childDepts = getByParentId(parentDept.getDeptId());
        for(MayanPlatDeptVo childDept : childDepts){
            allDept.add(childDept);
            loadChildDept(childDept,allDept);
        }
    }
}
